<template>
	<el-input v-model="filterText" placeholder="搜索分类" />
	<div class="flex ml-1 mt-2 mb-1">
		<Grid @click="onAll" style="width: 1.2em; height: 1.2em; margin-right: 8px" />
		<p @click="onAll">全部分类</p>
		<Edit style="width: 1.2em; height: 1.2em; margin-left: 115px" @click="handleEdit" />
	</div>

	<el-tree ref="treeRef" class="filter-tree" :data="treelist" :props="defaultProps" default-expand-all
		:filter-node-method="filterNode" @node-click="ontreeclick" />
	<edit-popup v-if="showEdit" ref="editRef" @close="close" @success="getLists" />
</template>

<script lang="ts" setup>
	import {
		adminLists
	} from '@/api/materials/list'
	import {
		ref,
		watch
	} from 'vue'
	import {
		ElTree
	} from 'element-plus'
	import EditPopup from './edit.vue'
	const emit = defineEmits(['ontreeclick','onAll'])
	const editRef = shallowRef < InstanceType < typeof EditPopup >> ()
	interface Tree {
		id: number
		label: string
		children ? : Tree[]
	}
	const showEdit = ref(false)
	const treelist = ref([])

	const filterText = ref('')
	const treeRef = ref < InstanceType < typeof ElTree >> ()

	const defaultProps = {
		children: 'children',
		label: 'name',
	}
	const handleEdit = async (data: any) => {
		showEdit.value = true
		await nextTick()
		editRef.value?.open('edit')
		editRef.value?.setFormData(data)
	}
	watch(filterText, (val) => {
		treeRef.value!.filter(val)
	})

	const filterNode = (value: string, data: Tree) => {
		if (!value) return true
		return data.name.includes(value)
	}
	const getRoleList = () => {
		adminLists().then((res: any) => {
			treelist.value = res
		})
	}
	const close = () => {
		showEdit.value = false
		getRoleList()
	}
	const ontreeclick = (val: any) => {
		emit('ontreeclick', val)
	}
	const onAll = ()=>{
		emit('onAll')
	}

	onMounted(() => {
		getRoleList()
	})
</script>
